const http = require("http");
const url = require("url");
const path = require("path");
const fs = require("fs");
const qs = require("querystring");

const notFound = (req, res) => {
  fs.readFile(path.join(__dirname, "404.html"), (err, data) => {
    if (err) {
      res.write(404, "not found");
    } else {
      res.writeHead(404, { "Content-Type": "text/html;charset='utf-8'" });
      res.write(data);
      res.end();
    }
  });
};

const writeDB = (chunk) => {
	fs.appendFile(path.join(__dirname, 'db'),chunk,err => {
		if(err) throw err;
		console.log('db instert', chunk && chunk.toString());
	})
}

//create a server object:
http
  .createServer(function (req, res) {
    // 1. 路由处理
    // 2. 静态资源托管
    // 3. HTTP verb
    // 4. store

    let pathName = url.parse(req.url).pathname;

    if (pathName.startsWith("/api")) {
      const method = req.method;
      if (method === "GET") {
        const query = qs.parse(url.parse(req.url).query); // ?a=1&b=2 => {}
        const resData = {
          code: 200,
          msg: "success",
          data: query,
        };
        res.end(JSON.stringify(resData));
        return;
      }
      if (method === "POST") {
        const contentType = req.headers["content-type"];
        if (contentType === "application/json") {
          let postData = "";
          req.on("data", (chunk) => {
            postData += chunk;
            writeDB(chunk);
          });
          req.on("end", () => {
            res.end(postData);
          });
        }
      }
    }

	// 如果输入/,重定向到index.html
    if (pathName === "/") {
      pathName = path.join(__dirname, "index.html");
    } else {
      pathName = `.${pathName}`;
    }
    console.log(pathName);
    const extName = path.extname(pathName);
    if (extName === ".html") {
      fs.readFile(pathName, { encoding: "utf-8" }, (err, data) => {
        if (err) {
          notFound(req, res);
        } else {
          res.writeHead(200, { "Content-Type": "text/html;charset='utf-8'" });
          res.write(data);
          res.end();
        }
      });
    }

    // res.write("Hello world! 你好,世界",); //write a response to the client
    // res.end();
    //end the response
  })
  .listen(8080); //the server object litens on port 8080
console.log("连接成功");
